package com.huawei.fastble;

import com.huawei.fastble.adapter.ServiceItemProvider;

import com.clj.fastble.data.BleDevice;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.bluetooth.ble.GattService;

import java.util.ArrayList;
import java.util.List;

public class ServiceListAbility extends Ability {
    private BleDevice device;
    private Text txtHeader;
    private ListContainer listContainer;
    private List<GattService> serviceList;
    private ServiceItemProvider provider;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_service);
        serviceList = new ArrayList<>();
        device = FastBleMyApplication.getBleDevice();

        txtHeader = (Text) findComponentById(ResourceTable.Id_txt_header);
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_service);

        serviceList.addAll(device.getBleDevice().getServices());
        txtHeader.setText("制造商数据：" + device.getManufacturer());

        provider = new ServiceItemProvider(this, serviceList);
        listContainer.setItemProvider(provider);
        listContainer.setItemClickedListener(
                new ListContainer.ItemClickedListener() {
                    @Override
                    public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                        intentToNext(serviceList.get(i));
                    }
                });
    }

    private void intentToNext(GattService service) {
        FastBleMyApplication.setGattService(service);
        Intent intent = new Intent();
        Operation operationBuilder =
                new Intent.OperationBuilder()
                        .withAbilityName("com.huawei.fastble.CharacteristicListAbility")
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .build();

        intent.setOperation(operationBuilder);
        startAbility(intent);
    }
}
